package com.example.hzz.criminalintent;

import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by huangzezhan on 2018/8/23.
 */

public class CrimeListFragment extends ListFragment {
    private static String TAG = "CrimeListFragment";
    private ArrayList<Crime> mCrimes = null;
    private TextView mTitle = null;
    private TextView mDate = null;
    private CheckBox mCheck = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.crime_titl);
        mCrimes = CrimeLab.getInstance(getActivity()).getCrimes();

//        ArrayAdapter<Crime> adapter =
//                new ArrayAdapter<Crime>(getActivity(),
//                        android.R.layout.simple_list_item_1,
//                        mCrimes);
        ArrayAdapter<Crime> adapter = new CrimeAdapter(mCrimes);
        setListAdapter(adapter);
    }


    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Crime c = (Crime) getListAdapter().getItem(position);
        Log.i(TAG, c.getmTitle() + " was clicked");
        Intent mIntent = new Intent(getActivity(),CrimePageActivity.class);
//        mIntent.setClass(getActivity(), CrimeActivity.class);
//        mIntent.putExtra("UUID", c.getmId());
//        Log.i(TAG, "Crime UUID=" + c.getmId());
        mIntent.putExtra("CRIME_ID",c.getmId());
        getActivity().startActivity(mIntent);
    }

    @Override
    public void onResume() {
        super.onResume();
        ((CrimeAdapter)getListAdapter()).notifyDataSetChanged();
    }

    private class CrimeAdapter extends ArrayAdapter<Crime> {
        public CrimeAdapter(ArrayList<Crime> crimes) {
            super(getActivity(), 0, crimes);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null);
            }

            Crime c = getItem(i);
            mTitle = (TextView) view.findViewById(R.id.criem_title);
            mTitle.setText(c.getmTitle());
            mDate = (TextView) view.findViewById(R.id.crime_date);
            mDate.setText(c.getmDate().toString());
            mCheck = (CheckBox) view.findViewById(R.id.crime_check);
            mCheck.setChecked(c.ismSolved());
            return view;
        }
    }
}
